﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;

namespace Extensil.Common
{
    public abstract class TaskBase
    {
        public delegate void StatusUpdate(object sender, ProgressChangedEventArgs e);
        public BackgroundWorker taskWorker = new BackgroundWorker();
        public AutoResetEvent resetEvent = new AutoResetEvent(false);
        public string Name;
        public string Param;
        public void UpdateStatus(int percentProgress, string statusMessage)
        {
            taskWorker.ReportProgress(percentProgress, "[" + Name + "]:" + statusMessage);
        }
        public abstract void Start(object param);
        public void Execute(StatusUpdate statusEvent)
        {
            taskWorker.WorkerReportsProgress = true;
            taskWorker.WorkerSupportsCancellation = true;
            taskWorker.DoWork += new DoWorkEventHandler(Execute);
            taskWorker.ProgressChanged += new ProgressChangedEventHandler(statusEvent);
            taskWorker.RunWorkerAsync();
            resetEvent.WaitOne();
            taskWorker.Dispose();
        }
        void Execute(object sender, DoWorkEventArgs e)
        {
            try
            {
                if(!e.Cancel)
                {
                    Start(Param);
                }
            }
            finally
            {
                resetEvent.Set();
            }
            
        }
    }
}
